import { BaseTool } from '../types';

export class CalculatorTool extends BaseTool {
  name = 'calculator';
  description = '执行基本的数学计算，支持加减乘除和简单函数';
  parameters = {
    type: 'object' as const,
    properties: {
      expression: {
        type: 'string',
        description: '要计算的数学表达式，例如: "2 + 3 * 4" 或 "Math.sqrt(16)"'
      }
    },
    required: ['expression']
  };

  async execute(args: { expression: string }): Promise<string> {
    try {
      const { expression } = args;
      
      // 安全的表达式验证
      const allowedPattern = /^[0-9+\-*/().\s\w,]+$/;
      if (!allowedPattern.test(expression)) {
        return '错误: 表达式包含不允许的字符';
      }

      // 允许的Math函数
      const allowedMathFunctions = ['abs', 'ceil', 'floor', 'round', 'sqrt', 'pow', 'sin', 'cos', 'tan', 'log', 'max', 'min'];
      const mathContext: Record<string, any> = {};
      allowedMathFunctions.forEach(func => {
        mathContext[func] = (Math as any)[func];
      });

      // 创建安全的执行环境
      const safeEval = new Function('Math', `
        const {${allowedMathFunctions.join(', ')}} = Math;
        return ${expression};
      `);

      const result = safeEval(Math);
      
      if (typeof result !== 'number' || !isFinite(result)) {
        return '错误: 计算结果无效';
      }

      return `计算结果: ${expression} = ${result}`;
    } catch (error) {
      return `计算错误: ${error instanceof Error ? error.message : '未知错误'}`;
    }
  }
}
